package com.zxhhyj.storm

import androidx.sqlite.driver.bundled.BundledSQLiteDriver
import com.zxhhyj.storm.database.Database
import com.zxhhyj.storm.schema.Table
import kotlin.test.Test


class HighLevelTest {

    class User(
        val id: Int,
        val name: String,
        val location: String?,
    )

    private object UserTable : Table<User>("t_user") {
        val id = int("id").primaryKey(true).bindTo(User::id)
        val name = varchar("name").bindTo(User::name)
        val location = varchar("location").nullable().bindTo(User::location)
    }

    private val database = Database(BundledSQLiteDriver().open("HighLevelTest.db"))

    init {
        database.createTable(UserTable, true)
    }

    @Test
    fun test() = database.beginTransaction {
        val userList = List(100) { index ->
            User(
                id = index + 1,
                name = "User${index + 1}",
                location = when ((index % 10)) {
                    0 -> "Beijing"
                    1 -> "Shanghai"
                    2 -> "Guangzhou"
                    3 -> "Shenzhen"
                    4 -> "Hangzhou"
                    5 -> "Chengdu"
                    6 -> "Xi'an"
                    7 -> "Wuhan"
                    8 -> "Nanjing"
                    9 -> "YGXQ"
                    else -> "Unknown"
                }
            )
        }

        try {
            database.batchInsert(UserTable, userList)
        } catch (e: Exception) {
            e.printStackTrace()
        }

        database
            .form(UserTable)
            .select(UserTable.id, UserTable.name)
            .groupBy(UserTable.id)
            .asKotlinSequence()
            .forEach {
                val id = it[UserTable.id]
                val name = it[UserTable.name]
                val location = it[UserTable.location]
                println("User: id=$id,name=$name,location=$location")
            }
    }
}